package com.wcar.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.wxpay.sdk.WXPayUtil;
import com.wcar.common.entity.*;
import com.wcar.common.util.WebUtil;
import com.wcar.common.vo.Result;
import com.wcar.order.dao.*;
import com.wcar.order.service.OrderService;
import com.wcar.order.utils.HttpClient;
import com.wcar.order.vo.OrderMobileVo;
import com.wcar.order.vo.OrderVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private StoreUserDao storeUserDao;
    @Autowired
    private ProductReviewDao productReviewDao;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private MobileOrderDao mobileOrderDao;
    @Autowired
    private UserBalanceDao userBalanceDao;
    @Autowired
    private UserIntegralDao userIntegralDao;
    @Autowired
    private UserIntegralLogDao userIntegralLogDao;
    @Resource
    private UserBalanceLogMapper userBalanceLogMapper ;
    @Autowired
    private ProductDao productDao;
    @Value("${weixin.appid}")
    private String appId;

    @Value("${weixin.mch_id}")
    private String mchId;

    @Value("${weixin.api_key}")
    private String apikey;

    @Override
    public Result<Page<ProductOrder>> getOrderList(OrderVo orderVo) {
        //获取token
        String token = WebUtil.getToken();
        ValueOperations<String, String> forValue = redisTemplate.opsForValue();
        String s = forValue.get("user:login:" + token);
        User user = JSON.parseObject(s, User.class);
        QueryWrapper<StoreUser> wrapper = new QueryWrapper<>();
        if(user.getUserId()!=1){
            wrapper.eq("user_id",user.getUserId());
        }
        List<StoreUser> storeUsers = storeUserDao.selectList(wrapper);
        ArrayList<Integer> userIds = new ArrayList<>();
        for (StoreUser storeUser : storeUsers) {
            userIds.add(storeUser.getStoreId());
        }
        Page<ProductOrder> page = new Page<>(orderVo.getCurrentPage(),orderVo.getPageSize());
        QueryWrapper<ProductOrder> query = new QueryWrapper<>();
        if(orderVo.getStatusCode()!=null){
            query.eq("status_code",orderVo.getStatusCode());
        }
        if(userIds.size()==0){
            return new Result<>(201,"获取订单信息成功",null);
        }
        query.in("to2.store_id",userIds);
        Page<ProductOrder> list = orderDao.getPage(page, query);
        return new Result<>(200,"获取订单信息成功",list);
    }

    @Override
    public Result<List<ProductOrder>> getOrderMobile(OrderMobileVo orderVo) {
        //获取token
        String token = WebUtil.getToken();
        ValueOperations<String, String> forValue = redisTemplate.opsForValue();
        String s = forValue.get("font:login:" + token);
        FrontUser user = JSON.parseObject(s, FrontUser.class);
        Page<ProductOrder> page = new Page<>(orderVo.getPageNo(),orderVo.getPageSize());
        QueryWrapper<ProductOrder> wrapper = new QueryWrapper<>();
        System.out.println(user.getUserId());
        wrapper.eq("user_id",user.getUserId());
        wrapper.orderBy(true,false,"id");
        if(orderVo.getStatusCode()!=null&&orderVo.getStatusCode()!=0){
            wrapper.eq("status_code",orderVo.getStatusCode());
        }
        List<ProductOrder> orderPage = orderDao.selectList(wrapper);
        for (ProductOrder order : orderPage) {
            if(order.getTotalAmount()==null){
                order.setTotalAmount(new BigDecimal(0));
            }
            if(order.getTotalIntegral()==null){
                order.setTotalIntegral(new BigDecimal(0));
            }
        }
        return new Result<>(200,"获取订单信息成功",orderPage);
    }

    @Override
    public Result updateStatus(Integer id) {
        ProductOrder order = orderDao.selectById(id);
        order.setStatusCode(43);
        int i = orderDao.updateById(order);
        return new Result<>(200,"修改订单成功",i);
    }

    @Override
    public Result updateBuyStatus(Integer id) {
        ProductOrder order = orderDao.selectById(id);
        order.setStatusCode(11);
        int i = orderDao.updateById(order);
        return new Result<>(200,"修改订单成功",i);
    }

    @Override
    public Result<ProductOrder> selectOneOrder(Integer id) {
        ProductOrder productOrder = orderDao.selectById(id);
        return new Result<>(200,"根据订单id查询订单成功",productOrder);
    }

    @Override
    public Result IntegralPay(ProductOrder order) {
        QueryWrapper<UserIntegral> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",order.getUserId());
        wrapper.eq("store_id",order.getStoreId());
        UserIntegral userIntegral = userIntegralDao.selectOne(wrapper);
        if (userIntegral==null){
            return new Result<>(500,"积分不足",null);
        }
        if(userIntegral.getCredits().compareTo(order.getTotalIntegral())>=0){
            userIntegral.setCredits(userIntegral.getCredits().subtract(order.getTotalIntegral()));
            userIntegralDao.updateById(userIntegral);
            UserIntegralLog userIntegralLog = new UserIntegralLog();
            userIntegralLog.setUserId(order.getUserId());
            userIntegralLog.setStoreId(order.getStoreId());
            userIntegralLog.setExpendScore(order.getTotalIntegral().intValue());
            userIntegralLog.setRechargeTime(new Date());
            userIntegralLogDao.insert(userIntegralLog);
            order.setUpdateTime(new Date());
            order.setPayTime(new Date());
            order.setPayType("1");
            orderDao.updateById(order);
            return new Result<>(200,"支付成功",null);
        } else{
            return new Result<>(500,"积分不足",null);
        }
    }

    @Override
    public Result<Product> PayFinish(Integer id) {
        ProductOrder productOrder = orderDao.selectById(id);
        productOrder.setStatusCode(41);
        int i = orderDao.updateById(productOrder);
        Product product = productDao.selectById(productOrder.getProductId());
        product.setTotalAmount(productOrder.getTotalAmount());
        product.setProductCount(productOrder.getProductCount());
        if(product.getNewPrice()==null){
            product.setNewPrice(new BigDecimal(0.0));
        }
        return new Result<>(200,"获取订单信息成功",product);
    }

    @Override
    public Result createWDPay(ProductOrder order) {
            String s = new String("损失"+order.getTotalAmount()+"大洋");
            QueryWrapper<UserIntegral> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id",order.getUserId());
            wrapper.eq("store_id",order.getStoreId());
            UserIntegral userIntegral = userIntegralDao.selectOne(wrapper);
            if(userIntegral.getCredits().compareTo(order.getTotalIntegral())>=0){
                try{
                    Map<String, String> params = new HashMap<>();//请求参数
                    params.put("appid", appId);
                    params.put("mch_id", mchId);
                    params.put("nonce_str", WXPayUtil.generateNonceStr());
                    params.put("body", s);
                    params.put("out_trade_no", order.getOrderNo());
                    //params.put("total_fee", new BigDecimal(order.getTotalFee()).multiply(new BigDecimal(100)).longValue() + "");
                    params.put("total_fee", new BigDecimal(0.01).multiply(new BigDecimal(100)).longValue() + "");
                    params.put("spbill_create_ip", "127.0.0.1");
                    params.put("notify_url", "http://localhost:9000/pay/back");
                    params.put("trade_type", "NATIVE");
                    HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
                    client.setHttps(true);//允许http协议
                    client.setXmlParam(WXPayUtil.generateSignedXml(params, apikey));//设置请求参数
                    //准备发送请求
                    client.post();
                    //获取请求响应结果
                    String content = client.getContent();
//				System.out.println(content);
                    Map<String, String> map = WXPayUtil.xmlToMap(content);
                    System.out.println(map);
                    //代码没问题,但是找不到符合要求的
                    if (map.get("result_code").equals("SUCCESS")) {
                        System.out.println("chenggong");
                        Map<String, String> result = new HashMap<>();
                        result.put("codeUrl", map.get("code_url"));
                        result.put("price", order.getTotalAmount()+"");
                        result.put("orderNo",  order.getOrderNo());
                        return new Result(200, "生成二维码成功", result);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return new Result(500, "订单失效", null);
    }

    @Override
    public Result createWeChat(String orderNo) {
        QueryWrapper<ProductOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no",orderNo);
        ProductOrder order = orderDao.selectOne(wrapper);
        if (order.getUserId() != null) {
            String s = new String("损失"+order.getTotalAmount()+"大洋");
            try {
                Map<String, String> params = new HashMap<>();//请求参数
                params.put("appid", appId);
                params.put("mch_id", mchId);
                params.put("nonce_str", WXPayUtil.generateNonceStr());
                params.put("body", s);
                params.put("out_trade_no", order.getOrderNo());
                //params.put("total_fee", new BigDecimal(order.getTotalFee()).multiply(new BigDecimal(100)).longValue() + "");
                params.put("total_fee", new BigDecimal(0.01).multiply(new BigDecimal(100)).longValue() + "");
                params.put("spbill_create_ip", "127.0.0.1");
                params.put("notify_url", "http://localhost:9000/pay/back");
                params.put("trade_type", "NATIVE");
                HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
                client.setHttps(true);//允许http协议
                client.setXmlParam(WXPayUtil.generateSignedXml(params, apikey));//设置请求参数
                //准备发送请求
                client.post();
                //获取请求响应结果
                String content = client.getContent();
//				System.out.println(content);
                Map<String, String> map = WXPayUtil.xmlToMap(content);
                System.out.println(map);
                //代码没问题,但是找不到符合要求的
                if (map.get("result_code").equals("SUCCESS")) {
                    System.out.println("chenggong");
                    Map<String, String> result = new HashMap<>();
                    result.put("codeUrl", map.get("code_url"));
                    result.put("price", order.getTotalAmount()+"");
                    result.put("orderNo",  order.getOrderNo());
                    return new Result(200, "生成二维码成功", result);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return new Result(500, "订单失效", null);
    }

    @Override
    public Result queryWeChatPayStatus(String orderNo) {
        QueryWrapper<ProductOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no",orderNo);
        ProductOrder order = orderDao.selectOne(wrapper);
        try {
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            HashMap<String, String> params = new HashMap<>();
            params.put("appid", appId);
            params.put("mch_id", mchId);
            params.put("out_trade_no", orderNo);
            params.put("nonce_str", WXPayUtil.generateNonceStr());
            client.setHttps(true);//允许http协议
            client.setXmlParam(WXPayUtil.generateSignedXml(params, apikey));//设置请求参数
            client.post();
            //获取请求响应结果
            String content = client.getContent();
            Map<String, String> map = WXPayUtil.xmlToMap(content);
            //代码没问题,但是找不到符合要求的
            if (map.get("trade_state").equals("SUCCESS")) {
                UserBalanceLog userBalanceLog = new UserBalanceLog();
                userBalanceLog.setUserId(order.getUserId());
                userBalanceLog.setStoreId(order.getStoreId());
                userBalanceLog.setExpenditure(order.getTotalAmount().intValue());
                userBalanceLog.setExpenditureTime(new Date());
                int insert = userBalanceLogMapper.insert(userBalanceLog);
                QueryWrapper<UserBalance> balanceQueryWrapper= new QueryWrapper<>();
                balanceQueryWrapper.eq("user_id",order.getUserId());
                balanceQueryWrapper.eq("store_id",order.getStoreId());
                UserBalance userBalance = userBalanceDao.selectOne(balanceQueryWrapper);
                userBalance.setAmount(userBalance.getAmount().subtract(order.getTotalAmount()));
                userBalanceDao.updateById(userBalance);
                order.setUpdateTime(new Date());
                order.setPayTime(new Date());
                order.setPayType("0");
                orderDao.updateById(order);
                return new Result(200,"支付成功",null);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(501,"支付失败",null);
    }

    @Override
    public Result queryWDPayStatus(ProductOrder productOrder) {
        try {
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            HashMap<String, String> params = new HashMap<>();
            params.put("appid", appId);
            params.put("mch_id", mchId);
            params.put("out_trade_no", productOrder.getOrderNo());
            params.put("nonce_str", WXPayUtil.generateNonceStr());
            client.setHttps(true);//允许http协议
            client.setXmlParam(WXPayUtil.generateSignedXml(params, apikey));//设置请求参数
            client.post();
            //获取请求响应结果
            String content = client.getContent();
            Map<String, String> map = WXPayUtil.xmlToMap(content);
            //代码没问题,但是找不到符合要求的
            if (map.get("trade_state").equals("SUCCESS")) {
                UserBalanceLog userBalanceLog = new UserBalanceLog();
                userBalanceLog.setUserId(productOrder.getUserId());
                userBalanceLog.setStoreId(productOrder.getStoreId());
                userBalanceLog.setExpenditure(productOrder.getTotalAmount().intValue());
                userBalanceLog.setExpenditureTime(new Date());
                userBalanceLogMapper.insert(userBalanceLog);
                QueryWrapper<UserBalance> balanceQueryWrapper= new QueryWrapper<>();
                balanceQueryWrapper.eq("user_id",productOrder.getUserId());
                balanceQueryWrapper.eq("store_id",productOrder.getStoreId());
                UserBalance userBalance = userBalanceDao.selectOne(balanceQueryWrapper);
                userBalance.setAmount(userBalance.getAmount().subtract(productOrder.getTotalAmount()));
                userBalanceDao.updateById(userBalance);
                UserIntegralLog userIntegral = new UserIntegralLog();
                userIntegral.setUserId(productOrder.getUserId());
                userIntegral.setStoreId(productOrder.getStoreId());
                userIntegral.setExpendScore(productOrder.getTotalIntegral().intValue());
                userIntegral.setRechargeTime(new Date());
                userIntegralLogDao.insert(userIntegral);
                productOrder.setUpdateTime(new Date());
                productOrder.setPayTime(new Date());
                orderDao.updateById(productOrder);
                return new Result(200,"支付成功",null);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(501,"支付失败",null);
    }

    @Override
    public Result delete(Integer id) {
        orderDao.deleteById(id);
        return new Result(200,"删除成功",null);
    }

    @Override
    public Result<Order> insert(ProductReview productReview) {
        productReview.setCreateTime(new Date());
        productReviewDao.insert(productReview);
        return new Result<>(200,"评价成功",null);
    }

    @Override
    public Result updateReviewStatus(Integer id) {
        QueryWrapper<ProductOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("id",id);
        ProductOrder order = orderDao.selectOne(wrapper);
        order.setId(id);
        order.setStatusCode(28);
        orderDao.updateById(order);
        return new Result<>(200,"订单状态修改成功",null);
    }

    @Override
    public Result cancelOrder(ProductOrder productOrder) {
        productOrder.setStatusCode(30);
        orderDao.updateById(productOrder);
        return new Result<>(200,"取消订单成功",null);
    }

    @Override
    public Result sendOutGoods(ProductOrder productOrder) {
        productOrder.setStatusCode(46);
        productOrder.setDeliverTime(new Date());
        orderDao.updateById(productOrder);
        return new Result<>(200,"发货成功",null);
    }
}
